<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2019/3/9
 * Time: 16:55
 */

namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\Lottery;
use app\admin\model\ProxyMoney;
use app\index\model\Comments;
use app\index\validate\Article as ArticleValidate;
use Pistis\PseudoRandom;
use think\Db;
use think\db\Where;
use think\Exception;
use think\facade\Session;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;

class Article extends Base {
    public function __construct()
    {
        parent::__construct();
        $this->model = new ArticleModel;
        $this->validate = new ArticleValidate;
    }

    /**
     * @param int $limit
     * @param int $page
     * @return \think\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($limit=10,$page=1){
//        p(\session(''));die;
        $where=new Where();
        $data = request()->post();
        $where[$this->model->getTable().'.status']=['neq',-1];
        if (Session::has('mc_id')) {
            $where[$this->model->getTable().'.mcid']=['eq',\session('mc_id')];
        }
        if($data){
            if($data['title']){
                $where[$this->model->getTable().'.title']=['like',"%".trim($data['title'])."%"];
            }
            if($data['status']){
                $where[$this->model->getTable().'.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[]= [$this->model->getTable().'.create_time','between time',[$start,$end]];
            }
        }
        $provinces = db('provinces')->select();
        $this->assign('provinces',$provinces);
        $list = $this->model->getList($where,$limit);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else{
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            return view();
        }
    }

    public function add($id=0){
        if($id){
            $info = $this->model->find($id);
            if($info['mcid']){
                $_info = db('mch')->where('id','eq',$info['mcid'])->find();
                $info['mch']=$_info['name'];
            }
            $this->assign('info',$info);
        }
        return view();
    }

    /**
     * 审核
     * @param int $id
     * @param int $status
     * @param string $fail_info
     */
    public function chack_status($id=0,$status=0,$fail_info=''){
        if(!$id || !$status){
            $this->__e('缺少参数');
        }
        $info = $this->model->get($id);
        if(!$info){
            $this->__e('文章不存在');
        }
        $info->status = $status;
        $info->fail_info = $fail_info;
        if(!$info->save()){
            $this->__e('操作失败');
        }
        $this->__s('操作成功');

    }

    /**
     * 设置区域
     * @param int $id
     * @param int $pro
     * @param int $city
     * @param int $area
     * @param string $address
     */
    public function add_address($id=0,$pro=0,$city=0,$area=0,$address=''){
        if(!$id){
            $this->__e('缺少参数');
        }
        $info = $this->model->get($id);
        if(!$info){
            $this->__e('文章不存在');
        }
        $info->pro = $pro;
        $info->city = $city;
        $info->area = $area;
        $info->address = $address;
        if(!$info->save()){
            $this->__e('操作失败');
        }
        $this->__s('操作成功');
    }

    /**
     * 添加文章
     * @return \think\Response
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function insert(){
        $data = request()->param();
        if(!$this->validate->check($data)){
            return $this->__e($this->validate->getError());
        }
        if(isset($data['mch']) && $data['mch']){
            $info = db('mch')
                ->where('name','eq',trim($data['mch']))
                ->find();
            if(!$info){
                return $this->__e('商户不存在');
            }
            $data['mcid'] = $info['id'];
            unset($data['mch']);
        }
        $data['content'] = htmlspecialchars($data['content']);
        $data['finish_time'] = strtotime($data['finish_time']);
        Db::startTrans();
        if(!$data['id']){
            unset($data['id']);
            $data['create_time']=time();
            $mc_id = \session('mc_id');
            if($mc_id){
                $mch = new \app\admin\model\Mch();
                $money = $mch->getPublishRealMoney($mc_id,self::$setting,$out1);
                if(!$money){
                    return $this->__e($out1);
                }
                $id = $this->model->save($data);
                if(!$id){
                    return $this->__e('添加失败');
                }
                $last_id = $this->model->id;
                $name = '发布活动|'.$data['title'];
                $result = $mch->consumer($this->model->id,$mc_id,$money,1,$out,$name);
                if(!$result){
                    return $this->__e($out);
                }
                $proxy = new \app\admin\model\Proxy();
                $_money = $proxy->getArticleMoney($name,$last_id,$mc_id,$money,$out2);
                if($result && $_money){
                    Db::commit();
                    return $this->__s('操作成功',['redirect'=>Url('article/index')]);
                }else{
                    $this->model->destory($last_id);
                    Db::rollback();
                    return $this->__e('添加失败');
                }
            }else{
                $id = $this->model->save($data);
                if(!$id){
                    Db::rollback();
                    return $this->__e('添加失败');
                }
                Db::commit();
                return $this->__s('操作成功',['redirect'=>Url('article/index')]);
            }
        }else{
            $data['update_time']=time();
            if(self::$mc_id){
                $data['status']= 1;
            }
            if(!$this->model->isUpdate(true)->save($data)){
                Db::rollback();
                return $this->__e('操作失败');
            }
            Db::commit();
            $this->__s('操作成功',['redirect'=>Url('article/index')]);
        }
    }

    /**
     * 删除
     * @param int $id
     * @throws \Exception
     */
    public function del($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        $result = $this->model->destory($id,$out);
        if(!$result){
            $this->__e($out);
        }
        $this->__s('操作成功');
    }

    /**
     * @param int $id
     * @param int $limit
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function comment($id=0,$limit=10){
        $data = request()->post();
        $where = new Where();
        $where['think_comments.aid']=$id;
        if($data){
            if($data['content']){
                $where['think_comments.content']=['like',"%".trim($data['content'])."%"];
            }
            if($data['status']){
                $where['think_comments.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where['think_comments.create_time']= ['between time',[$start,$end]];
            }
        }
        $model = new Comments();
        $order = 'think_comments.is_top desc,think_comments.create_time desc';
        $list = $model->getList($where,'',$order,$limit);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else{
            $info = $this->model->find($id);
            $this->assign('total',$list->total());
            $this->assign('list',$list);
            $this->assign('info',$info);
            return view();
        }
    }

    /**
     * 置顶
     * @param int $id
     * @return \think\Response
     */
    public function is_top($id=0){
        if(!$id){
            return $this->__e('缺少参数');
        }
        $model = new Comments();
        $mch = $model->get($id);
        if(!$mch){
           return $this->__e('评论不存在');
        }
        $mch->is_top = ($mch['is_top']==0)?1:0;
        if(!$mch->save()){
           return $this->__e('操作失败');
        }
        return $this->__s('操作成功');
    }

    /**
     * @param int $id
     * @param int $status
     * @return \think\Response
     */
    public function comment_status($id=0,$status=0){
        if(!$id || !$status){
           return $this->__e('缺少参数');
        }
        $model = new Comments();
        $mch = $model->get($id);
        if(!$mch){
            return $this->__e('评论不存在');
        }
        $mch->status = $status;
        if(!$mch->isUpdate(true)->save()){
            return $this->__e('操作失败');
        }
        $this->__s('操作成功');
    }

    /**
     * 回调
     * @param $id
     * @param $content
     */
    public function reply($id,$content){
        $model = new Comments();
        $result = $model->reply($id,$content);
        if(!$result){
            $this->__e('回复失败');
        }
        $this->__e('回复成功');
    }

    /**
     * @param int $id
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function lottery($id=0){
        $data = request()->post();
        $where['aid'] = $id;
        if($data){
            if($data['prize']){
                $where['prize']=['like',"%".trim($data['prize'])."%"];
            }
            if($data['status']){
                $where['status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where[]= ['create_time','between time',[$start,$end]];
            }
        }
        $info = $this->model->find($id);
        $this->assign('info',$info);
        $m = new Lottery();
        $list = $m->getList($where,10);
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else {
            $this->assign('list', $list);
            $this->assign('total', $list->total());
            return view();
        }
    }

    public function lottery_add($id=0){
        $info = $this->model->find($id);
        $provinces = db('provinces')->select();
        $this->assign('info',$info);
        $this->assign('provinces',$provinces);
        return view();
    }

    public function lottery_status($id=0,$status=0){
        if(!$id || !$status){
            $this->__e('缺少参数');
        }

        $model = new Lottery();
        $info = $model->find($id);
        if(!$info){
            $this->__e('奖项不存在');
        }
        $info->status = $status;
        if(!$info->save()){
            $this->__e('操作失败');
        }
        $this->__s('操作成功');
    }

    /**
     * 删除
     * @param int $id
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function del_lottery($id=0){
        if(!$id){
            $this->__e('缺少参数');
        }
        $model = new Lottery();
        $result = $model->delete_lottery($id,$out);
        if(!$result){
            $this->__e($out);
        }
        $this->__s('删除成功');
    }

    /**
     * @param int $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_pro($id=0){
        $provinces = db('provinces')->select();
        $info = $this->model->field('id,pro,city,area')->find($id);
        $this->__s('',['info'=>$info,'list'=>$provinces]);
    }

    public function get_city($pid,$id=0){
        $list =  db('cities')->where('provinceid','eq',$pid)->select();
        $info = $this->model->field('id,pro,city,area')->find($id);
        $this->__s('',['info'=>$info,'list'=>$list]);
    }

    public function get_areas($cid,$id=0){
        $list =  db('areas')->where('cityid','eq',$cid)->select();
        $info = $this->model->field('id,pro,city,area')->find($id);
        $this->__s('',['info'=>$info,'list'=>$list]);
    }

    public function lottery_insert($id=0,$aid=0){
        $data = request()->post();
        unset($data['q']);
        $validate = new \app\admin\validate\Lottery();
        if(!$validate->check($data)){
           return $this->__e($validate->getError());
        }
        $model = new Lottery();
        if($id){
            $data['update_time']=time();
        }else{
          $data['create_time']=time();
          $result = $model->addNew($data,$out);
          if(!$result){
            return $this->__e($out);
          }
          return $this->__s('添加成功',['redirect'=>Url("article/lottery/id/{$aid}")]);
        }
    }

    /**
     * @param int $id
     * @return \think\Response|\think\response\View
     * @throws \think\exception\DbException
     */
    public function lottery_log($id=0){
        $data = request()->post();
        $model = new \app\admin\model\LotteryLog();
        $where          = new Where;
        $where[$model->getTable().'.aid']= $id;
        if($data){
            if($data['name']){
                $m = new \app\admin\model\Member();
                $list = $m
                    ->field('id,nickname')
                    ->whereLike('nickname',"%".trim($data['name'])."%")
                    ->select();
                $ids = [];
                foreach ($list as $v){
                    array_push($ids,$v['id']);
                }
                $where[$model->getTable().'.mid']    = ['in',$ids];
//                $where[]=[$model->getTable().'.mid','in',substr($ids,1)];
            }
            if($data['status']){
                $where['think_lottery_log.status']=$data['status'];
            }
            if($data['date']){
                $t = explode('~',$data['date']);
                $start = strtotime($t[0]);
                $end = strtotime($t[1]);
                $where['think_lottery_log.create_time']= ['between time',[$start,$end]];
            }
        }
        $info = $this->model->find($id);
        $this->assign('info',$info);
        $list = $model->getList($where,10);
//        p($list);die;
        if(request()->isAjax()){
            return $this->__s('',$list);
        }else {
            $this->assign('list', $list);
            $this->assign('total', $list->total());
            return view();
        }
    }

    public function create_qrcode($id=0){
        if(!$id){
            $this->error('缺少参数');
        }
        $info = $this->model->find($id);
        $this->assign('info',$info);
        $provinces = db('provinces')->select();
        $this->assign('provinces',$provinces);
        return view();
    }

    /**
     * 生成二维码
     * @param int $aid
     * @param int $mc_id
     * @param int $type
     * @param string $pro
     * @param string $city
     * @param string $area
     * @param string $address
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function article_qrcode($aid=0,$mc_id=0,$type=0,$pro='',$city='',$area='',$address=''){
        $_address = '';
        if($pro){
            $pro = explode('_',$pro);
            $_address .= $pro[1];
        }
        if($city){
            $city = explode('_',$city);
            $_address .= '_'.$city[1];
        }
        if($area){
            $area = explode('_',$area);
            $_address .= '_'.$area[1];
        }
        if($address){
            $_address .= '_'.$address;
        }
        $info = $this->model->get($aid);
        if(!$info){
            return $this->__e('活动不存在');
        }
        if($info['qrcode']){
            return $this->__e('您已经生成二维码了');
        }
        $price = $this->model->generateQrcodePrice($type);
        if(!$price){
            return $this->__e('参数错误');
        }
        $log = new \app\admin\model\Mch();
        $proxy = new \app\admin\model\Proxy();
        $mid = $proxy->getPoxyMidByAid($info['id']);
        $result = $log->consumer($aid,$mc_id,$price,3,$out);
        if(!$result){
            return $this->__e($out);
        }
        $_address = $_address ? $_address : '中国';
        $host = request()->server()['SERVER_NAME'];
        $url = "http://{$host}/client/detail.html?id={$aid}&location={$_address}&shareId={$mid}";
        $qrcode = new BaconQrCodeGenerator();
        $data = $qrcode
            ->encoding('UTF-8')
            ->format('png')
            ->merge('./static/AdminLTE/img/avatar.gif',.15,true)
            ->size(200)
            ->margin(1)
            ->errorCorrection('H')
//            ->color(255,0,255)
            ->generate("{$url}&".PseudoRandom::hex());
        $data = base64_encode($data);
        $info->qrcode = $data;
        if(!$info->save()){
            return $this->__e('生成失败');
        }
        return $this->__s('生成成功');
    }

    /**
     *
     * @param int $aid
     * @return \think\Response
     */
    public function article_qrcode1($aid=0){
        $info = $this->model->get($aid);
        if($info['qrcode']){
            return $this->__e('已经生成二维码了');
        }
        $host = request()->server()['SERVER_NAME'];
        $url = "http://{$host}/client/detail.html?id={$aid}";
        $data =qrcode("{$url}&".time());
        $info->qrcode = $data;
        if(!$info->save()){
            return $this->__e('生成失败');
        }
        return $this->__s('生成成功');
    }

    /**
     * @param int $id
     * @return \think\Response
     * @throws Exception\DbException
     */
    public function get_qrcode($id=0){
        if(!$id){
            return $this->__e('缺少参数');
        }
        $info = $this->model->field('id,qrcode')->get($id);
        if(!$info){
            return $this->__e('活动不存在');
        }
        if(!$info['qrcode']){
            return $this->__e('没有生成活动二维码');
        }
        return $this->__s('获取成功',$info);
    }
}